import datetime
import glob
import subprocess
import urllib

from pynput.keyboard import Controller,Key
from flask import Flask, jsonify, Response, request, session,send_file, redirect, url_for, abort,render_template
from urllib.parse import urlparse, parse_qs, urlunparse, urlencode, quote
from pathlib import Path
import html2
import os
potplayer_path="potplayer\\PotPlayerMini64.exe"
def convert_path1(path):
    return path.replace("\\", "/")
def search_file(path,filename):
    results = []

    # 使用通配符搜索文件
    for item in glob.glob(os.path.join(path, filename)):
        if os.path.isfile(item):
            results.append(['file', convert_path1(item)])
        elif os.path.isdir(item):
            results.append(['dir', convert_path1(item)])

    return results
def format_number(num):
    return "{:,}".format(num)
def bytes_to_mb(bytes):
    return round(bytes / (2 ** 20), 2)
def convert_timestamp(timestamp):
    dt = datetime.datetime.fromtimestamp(timestamp)
    formatted_dt = dt.strftime("%Y年%m月%d日，%H:%M:%S")
    return formatted_dt
def get_drives():
    drives = []
    result = subprocess.run(['wmic', 'logicaldisk', 'get', 'caption'], capture_output=True, text=True)
    if result.returncode == 0:
        for line in result.stdout.splitlines():
            if line.strip() != '':
                drives.append(["dir",line.strip()+"/"])
    return drives
filep=[]
app = Flask(__name__, template_folder=os.getcwd()+'\\template')
def is_directory(path):
    if os.path.isdir(path):
        return True
    else:
        return False
def convert_path(path):
    return path.replace('\\', '\\\\')
@app.route('/')
def default():
    return redirect("/index.html")
@app.route('/<path>')
def index(path):
    return send_file(os.getcwd()+"\\index\\"+path)
@app.route('/about/test2.png')
def abouttext2():
    return send_file("template\\test2.png")
@app.route('/rename', methods=['POST'])
def rename():
    referrer = request.referrer
    url = referrer
    parsed_url = urlparse(url)
    query_params = parse_qs(parsed_url.query)
    path = query_params.get('path', [''])[0]
    原文件名=os.path.basename(urllib.parse.unquote(path))
    新文件名=request.form.get('filename')
    if 原文件名==新文件名:# 如果重命名失败
        #print(原文件名)
        return html2.生成网页对话框("重命名失败","重命名失败(欲修改的文件名已存在)","错误","重命名失败")
    if 原文件名!=新文件名:#将尝试开始重命名文件
        if os.path.exists(os.path.dirname(path)+"\\"+新文件名):#判断新文件名是否被占用
            return html2.生成网页对话框("重命名失败","重命名失败(旧文件名等于新文件名)","错误","重命名失败")
        else:
            os.rename(path, os.path.dirname(path) + "\\" + 新文件名)
            if os.path.exists(os.path.dirname(path) + "\\" + 新文件名):
                query_params['path'] = quote(os.path.dirname(path) + "\\" + 新文件名)  # 修改路径参数
                query_params['action'] = 'withopen'
                modified_url = urlunparse(parsed_url._replace(query=urlencode(query_params)))
                print(urllib.parse.unquote(modified_url))
                return redirect(urllib.parse.unquote(modified_url))
            else:
                return html2.生成网页对话框("重命名失败","重命名失败(可能是权限问题，或目录只读)","错误","重命名失败(可能是权限问题，或目录只读)")

@app.route('/file')
def file():
    search=""
    device = ""
    filep.clear()
    url = request.url
    parsed_url = urlparse(url)
    query_params = parse_qs(parsed_url.query)
    try:
        path = query_params.get('path', [''])[0]
    except:pass
    try:
        action = query_params.get('action', [''])[0]
    except:pass
    try:
        search = query_params.get('search', [''])[0]
    except:pass
    try:
        device = query_params.get('device', [''])[0]
    except:pass

    if action!="" and os.path.exists(path) == True:
        if action=="withopen":
            data = {
                'filename':os.path.basename(path),
                'filetype': html2.get_extension(path)+"("+html2.get_mimetype(path)+")",
                'filesize':str(bytes_to_mb(float(os.path.getsize(path))))+"MB"+"("+str(format_number(os.path.getsize(path)))+"字节)",
                'filepath':path,
                'dirpath':os.path.dirname(path),
                'filesize1':os.path.getsize(path),
                'fwsj':convert_timestamp( os.path.getatime(path)),
                'xgsj': convert_timestamp( os.path.getmtime(path)),
                'cjsj': convert_timestamp( os.path.getctime(path))
            }  # 后端数据
            #print(os.path.basename(path))
            return render_template('about.html', data=data)
        elif action=="download":
            #print(path)
            #return send_file(path, as_attachment=True)
            return send_file(path)
        elif action == "view":
            with open(path, "rb") as f:
                file = f.read()
            response = Response(file)
            response.headers['Content-Type'] = html2.get_mimetype(convert_path(path))
            return response
        #这里 处理 远程 播放 事件，可以 单 台文 件 提供服务器 让多 个 远程播放 客户 端 播放
        elif action == "play":
            if device=="":
                return redirect(f'/file?path={path}&action=play&device=local')
            elif device == "local":#这里是服务器本机播放
                os.system(potplayer_path+" "+"\""+path+"\""+" /current")#这里是potplayer播放器
                return redirect(f'/file?path={path}&withopen=withopen')

        elif action == "md5":
            md5=html2.calculate_file_md5(path)
            crc32=html2.calculate_file_crc32(path)
            sha256=html2.calculate_file_sha256(path)
            r="md5:"+md5+"\n"+"crc32:"+str(crc32)+"\n"+"sha256:"+sha256+"\n"
            response =  Response(r.encode())
            response.headers['Content-Type'] = "text/plain"
            return response
    elif (search!= ""):
        return html2.生成file列表(search_file(path,search))
    elif os.path.isfile(path):
        file_name = os.path.basename(path)
        return redirect(f'/file?path={path}&action=withopen')
    elif (path == ""):
        #print(get_drives())
        return html2.生成file列表(get_drives())
    elif os.path.isdir(path):
        dir_path = convert_path(path)
        files = Path(dir_path).glob('*')
        for file in files:
            if file.is_file():
                filep.append(["file",file.absolute().as_posix()])
            elif file.is_dir():
                filep.append(["dir",file.absolute().as_posix()])
        #print(filep)
        return html2.生成file列表(filep,path)
    elif (os.path.exists(path) == False):
        abort(404, description="文件未找到")
if __name__ == '__main__':
    app.run(host="0.0.0.0", port=80, debug=True)